package com.example.monitor.service.impl;

import com.example.monitor.model.DTO.AbnormalTypeQueryDTO;
import com.example.monitor.model.VO.AbnormalTypeVO;
import com.example.monitor.model.VO.ResultVO;
import com.example.monitor.repository.AlarmRecordRepository;
import com.example.monitor.service.AbnormalTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AbnormalTypeServiceImpl implements AbnormalTypeService {

    private final AlarmRecordRepository alarmRecordRepository;

    @Override
    public ResultVO<List<AbnormalTypeVO>> getAbnormalTypeDistribution(AbnormalTypeQueryDTO queryDTO) {
        // 解析时间范围
        Timestamp startTime = parseTimeRange(queryDTO.getTimeRange());

        // 查询原始数据
        List<Object[]> rawData = alarmRecordRepository.countByAlarmType(
                queryDTO.getWorkshop(),
                startTime);

        // 计算总数用于计算百分比
        int total = rawData.stream()
                .mapToInt(arr -> ((Number)arr[1]).intValue())
                .sum();

        // 转换为VO列表
        List<AbnormalTypeVO> result = rawData.stream()
                .map(arr -> new AbnormalTypeVO(
                        (String) arr[0],
                        ((Number) arr[1]).intValue(),
                        total > 0 ?
                                Math.round(((Number)arr[1]).doubleValue() / total * 100 * 10) / 10.0 :
                                0.0
                ))
                .collect(Collectors.toList());

        return ResultVO.success("查询成功", result);
    }

    private Timestamp parseTimeRange(String timeRange) {
        if (timeRange == null) {
            return Timestamp.valueOf(LocalDateTime.now().minusDays(7));
        }
        switch (timeRange) {
            case "1天": return Timestamp.valueOf(LocalDateTime.now().minusDays(1));
            case "1周": return Timestamp.valueOf(LocalDateTime.now().minusWeeks(1));
            case "1月": return Timestamp.valueOf(LocalDateTime.now().minusMonths(1));
            default: return Timestamp.valueOf(LocalDateTime.now().minusDays(7));
        }
    }
}
